#include "sc_graphics.h"

#include <GL/glew.h>
#include "filesystem/be_file.h"
#include "filesystem/be_filesystem.h"

ScGraphics::ScGraphics()
{
	//Initialise default GL state

	//Hint for everything to be nicest
	m_graphicsSystem.hint(GL_FOG_HINT, GL_NICEST);
	m_graphicsSystem.hint(GL_FRAGMENT_SHADER_DERIVATIVE_HINT, GL_NICEST);
	m_graphicsSystem.hint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
	m_graphicsSystem.hint(GL_LINE_SMOOTH_HINT, GL_NICEST);
	m_graphicsSystem.hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	m_graphicsSystem.hint(GL_POINT_SMOOTH_HINT, GL_NICEST);
	m_graphicsSystem.hint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
	m_graphicsSystem.hint(GL_TEXTURE_COMPRESSION_HINT, GL_NICEST);

	//Smooth shading
	m_graphicsSystem.shadeModel(GL_SMOOTH);

	//Enable back face culling
	//m_graphicsSystem.enable(GL_CULL_FACE);
	//m_graphicsSystem.cullFace(GL_BACK);

	//Enable depth test
	m_graphicsSystem.enable(GL_DEPTH_TEST);

	//Alpha blending
	//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	//glEnable (GL_BLEND); 

	glEnable ( GL_ALPHA_TEST );
	glAlphaFunc ( GL_GREATER, 0.5f ) ;

	//Set default light model settings
	m_graphicsSystem.lightModel(GL_LIGHT_MODEL_AMBIENT, Vector4f(0.7f, 0.7f, 0.7f, 1.0f));
	m_graphicsSystem.lightModel(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
	m_graphicsSystem.lightModel(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
	m_graphicsSystem.lightModel(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);

	//Set one directional light by default
	BeDirectionalLight light;
	light.setDirection(Vector3f(1,1,0));
	light.setSpecular(Vector4f(1,1,1,1));
	m_graphicsSystem.applyLight(GL_LIGHT0, &light);

	//Set the default material
	m_graphicsSystem.applyMaterial(GL_FRONT_AND_BACK, 0);

	//Disable lighting
	m_graphicsSystem.disable(GL_LIGHTING);

	//Set default matrices
	m_graphicsSystem.matrixLoadIdentity(GL_PROJECTION);
	m_graphicsSystem.matrixLoadIdentity(GL_MODELVIEW);

	BeFile vertexShaderFile;
	if ( BeFilesystem::Instance()->load( vertexShaderFile, "shaders/default.vert") )
	{
		std::string string;
		vertexShaderFile.getFile(string);
		m_vertexShader.source(string);
		m_vertexShader.compile();
		m_program.attachShader(&m_vertexShader);
	}

	BeFile fragmentShaderFile;
	if ( BeFilesystem::Instance()->load( fragmentShaderFile, "shaders/default.frag") )
	{
		std::string string;
		fragmentShaderFile.getFile(string);
		m_fragmentShader.source(string);
		m_fragmentShader.compile();
		m_program.attachShader(&m_fragmentShader);
	}

	m_program.link();
	
}

ScGraphics::~ScGraphics()
{

}
